package com.example.demon.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

@Component
public class JwtTokenUtil {
    public static final String TOKEN_HEADER = "Authorization";
    public static final String Token_PREFIX = "Bearer ";
    public static final String Token_KEY = "/BGlTrn5ozD0lD99sSoAqS2hbz4tNpPsmpZT4ren7WA=";
    public static final Long expiration = 3600000000L;


    /**
     * 生成token令牌
     *
     * @param userDetails 用户
     * @return 令token牌
     */
    public String generateToken(UserDetails userDetails) {
        Date expirationDate = new Date(System.currentTimeMillis() + expiration);
        List<String> roles = userDetails.getAuthorities()
                .stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList());
        String token = Jwts.builder().claim("rol", roles)
                .setSubject(userDetails.getUsername())
                .setExpiration(expirationDate)
                .signWith(Keys.hmacShaKeyFor(Token_KEY.getBytes())).compact();
        return "Bearer " + token;
    }

    /**
     * 从令牌中获取用户名
     *
     * @param token 令牌
     * @return 用户名
     */
    public String getUsernameFromToken(String token) {
        String username;
        try {
            Jws<Claims> claimsJws = Jwts.parserBuilder().setSigningKey(Token_KEY.getBytes()).build()
                    .parseClaimsJws(token.replace(Token_PREFIX, ""));
            username = claimsJws.getBody().getSubject();
        } catch (Exception var4) {
            username = null;
        }

        return username;
    }

    /**
     * 判断令牌是否过期
     *
     * @param token 令牌
     * @return 是否过期
     */
    public Boolean isTokenExpired(String token) {
        try {
            Jws<Claims> claimsJws = Jwts.parserBuilder().setSigningKey(Token_KEY.getBytes()).build()
                    .parseClaimsJws(token.replace("Bearer ", ""));
            Date expiration = claimsJws.getBody().getExpiration();
            return expiration.before(new Date());
        } catch (Exception e) {
            return false;
        }
    }
}
